import { computed, defineComponent, reactive, ref } from "vue";
import Page from "@/components/public/page/page";
import { CardWithTitle } from "@/components/public/card/card";
import styles from "./discountSetPage.module.less";
import LTable from "@/components/public/lTable/lTable";
import discountService from "@/modules/channelManagement/channelUsersPage/discountSetPage/discountSetPage.service";
import useNavigator from "@/hooks/useNavigator";
import { DeleteOutlined, PlusOutlined } from "@ant-design/icons-vue";
import LPopup from "@/components/public/lPopup/lPopup";
import Add from "./popup/add/add";
import { $discountSave } from "@/api/user/user";
import { message, Modal } from "ant-design-vue";
import Edit from "./popup/edit/edit";


export default defineComponent({
  name: 'discountSetPage',
  setup() {
    const navigator = useNavigator();
    const state = reactive({
      toolbar: {
        left: [
          "refresh",
          {
            el: () => (
              <a-button v-slots={{ icon: () => <PlusOutlined /> }} onClick={() => { addDiscountPopup.value.open() }}>添加产品</a-button>
            )
          },
          {
            el: () => (
              <a-button type="primary" danger v-slots={{ icon: () => <DeleteOutlined /> }} onClick={() => { discountDelete() }}>删除产品</a-button>
            )
          },
        ],
        right: ["filter"],
      },
      columns: [
        {
          title: "产品ID",
          dataIndex: "insurance_id",
          key: "id",
          align: "center",
          width: "50px",
        },
        {
          title: "产品名称",
          dataIndex: "name",
          align: "center",
          width: "200px",
        },
        {
          fixed: "right",
          title: "操作",
          dataIndex: "operation",
          align: "center",
          width: "100px",
        }
      ],
      dataSource: [
        {
          insurance_id: 123,
          name: '优游保-境内游(基础版)',
        },
        {
          insurance_id: 123,
          name: '优游保-境内游(全面版)',
        },
      ],
      loading: false,
      insurance_ids: [],
      query: {
        user_id: navigator.route?.query?.id || '',
      },
      pagination: {
        total: 0,
        current: 1,
        pageSize: 10,
      },
    } as any);

    //删除产品
    const discountDelete = () => {
      if (state.insurance_ids.length === 0) {
        message.error('请选择产品');
        return
      }
      Modal.confirm({
        title: "提示",
        content: "确认删除?",
        onOk: async () => {
          $service.delete({
            user_id: state.query.user_id,
            insurance_ids: state.insurance_ids,
          }).then((res: any) => {
            state.insurance_ids = [];
            message.success('删除成功');
            LTableRef.value.$fetchTableData();
          })
        }
      })
    }

    // 表格状态变更
    const tableChangeHandler = (pag: { pageSize: number; current: number }) => {
      state.pagination.current = pag.current;
      state.pagination.pageSize = pag.pageSize;
    };

    // 选中项变更
    const onSelectChange = (changableRowKeys: any[]) => {
      state.insurance_ids = changableRowKeys;
    };
    const rowSelection = computed(() => {
      return {
        selectedRowKeys: state.insurance_ids,
        fixed: true,
        onChange: onSelectChange,
      };
    });

    //添加产品
    const addConfirm = (e: any) => {
      if (e.insurance_id.length === 0) {
        message.error('请选择产品');
        return
      }
      if (!e.rate) {
        message.error('请输入折扣');
        return
      }
      if (e.rate === 0.3 || e.rate === 0) {
        message.error('折扣不符合要求，请重新输入')
        return
      }
      $discountSave({
        user_id: Number(navigator.route?.query.id),
        insurance_ids: e.insurance_id,
        rate: e.rate
      }).then((res: any) => {
        message.success('添加成功!');
        LTableRef.value.$fetchTableData();
        addDiscountPopup.value.close();
      })
    }
    const LTableRef = ref(null as any);
    const $service = new discountService();
    const addDiscountPopup = ref(null as any);
    const editPopup = ref(null as any);

    return () => (
      <Page>
        <CardWithTitle title="已配置折扣的产品">
          <LTable
            ref={LTableRef}
            toolbar={state.toolbar}
            service={$service}
            v-model={state}
          >
            <a-table
              bordered={true}
              scroll={{ x: "max-content" }}
              dataSource={state.dataSource}
              columns={state.columns}
              pagination={state.pagination}
              loading={state.loading}
              onChange={tableChangeHandler}
              row-selection={rowSelection.value}
              rowKey="insurance_id"
              v-slots={{
                bodyCell: ({ column, record }: any) => {
                  //操作
                  if (column.dataIndex === "operation") {
                    return (
                      <div class="operation">
                        <a-button type="primary" onClick={() => { editPopup.value.open(record) }}>折扣编辑</a-button>
                      </div>
                    )
                  }
                },
              }}
            />
          </LTable>
        </CardWithTitle>
        <LPopup title="选择未配置折扣的产品" ref={addDiscountPopup}>
          <Add onCancel={() => { addDiscountPopup.value.close() }} onConfirm={(e: number[]) => { addConfirm(e) }} />
        </LPopup>
        <Edit
          ref={editPopup}
          service={$service}
          onChange={() => { LTableRef.value.$fetchTableData(); }}
        />
      </Page>
    )
  }
})